<template>
    <div class="shige-container" :class="{ 'dark-mode': isDarkMode }">
        <!-- 顶部导航栏 -->
        <header class="header">
            <div class="logo">诗韵流芳</div>
            <div class="search-box">
                <input type="text" placeholder="搜索诗词、诗人..." v-model="searchQuery" @keyup.enter="searchPoems" @input="handleSearchInput">
                <button class="search-btn" @click="searchPoems">
                    <i class="icon-search">🔍</i>
                </button>
            </div>
            <div class="theme-toggle" @click="toggleTheme">
                <i v-if="isDarkMode" class="icon-sun">☀️</i>
                <i v-else class="icon-moon">🌙</i>
            </div>
        </header>

        <!-- 主内容区 -->
        <main class="main-content">
            <!-- 推荐诗词区 -->
            <section class="section poem-recommendation">
                <h2 class="section-title">今日推荐
                    <i class="refresh-icon" @click.stop="refreshDailyRecommendations">🔄</i>
                </h2>
                <div class="poem-cards">
                    <div v-for="(poem, index) in uniqueRecommendedPoems" :key="index" class="poem-card"
                        @click="showPoemDetail(poem)">
                        <h3 class="poem-title">{{ poem.title }}</h3>
                        <div class="poem-author">{{ poem.dynasty }} · {{ poem.author }}</div>
                        <div class="poem-excerpt">{{ poem.excerpt }}</div>
                    </div>
                </div>
            </section>

            <!-- 主题分类区 -->
            <section class="section theme-categories">
                <h2 class="section-title">诗词主题</h2>
                <div class="theme-list">
                    <div v-for="(theme, index) in themeCategories" :key="index" class="theme-item"
                        @click="selectTheme(theme)">
                        <div class="theme-icon">{{ theme.icon }}</div>
                        <div class="theme-name">{{ theme.name }}</div>
                    </div>
                </div>
            </section>

            <!-- 诗人推荐区 -->
            <section class="section poet-recommendation">
                <h2 class="section-title">诗人推荐
                    <i class="refresh-icon" @click.stop="refreshPoetRecommendations">🔄</i>
                </h2>
                <div class="poet-list">
                    <div v-for="(poet, index) in recommendedPoets" :key="index" class="poet-item"
                        @click="showPoetDetail(poet)">
                        <div class="poet-avatar">{{ poet.avatar }}</div>
                        <div class="poet-info">
                            <div class="poet-name">{{ poet.name }}</div>
                            <div class="poet-dynasty">{{ poet.dynasty }}</div>
                        </div>
                    </div>
                </div>
            </section>

            <!-- 诗人详情弹窗 -->
            <div v-if="showPoetDetailModal" class="poet-detail-modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>{{ currentPoet.name }}</h3>
                        <span class="close-btn" @click="closePoetDetail">×</span>
                    </div>
                    <div class="modal-body">
                        <div class="poet-detail-info">
                            <div class="poet-detail-avatar">{{ currentPoet.avatar }}</div>
                            <div class="poet-detail-meta">
                                <div class="poet-detail-dynasty">{{ currentPoet.dynasty }}</div>
                                <div class="poet-detail-description">{{ currentPoet.description }}</div>
                            </div>
                        </div>
                        <div class="poet-detail-section">
                            <h4>代表作品</h4>
                            <div class="poet-works">
                                <span v-for="(work, idx) in currentPoet.famousWorks" :key="idx"
                                    class="poet-work-item">{{ work }}</span>
                            </div>
                        </div>
                        <div class="poet-detail-section">
                            <h4>评价</h4>
                            <p>{{ currentPoet.evaluation }}</p>
                        </div>
                        <div class="poet-detail-section">
                            <h4>了解更多</h4>
                            <a :href="currentPoet.wikiLink" target="_blank" class="wiki-link">查看百科</a>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <!-- 底部操作区 -->
        <footer class="footer">
            <div class="nav-item" :class="{ 'active': activeTab === 'home' }" @click="navigateTo('home')">
                <i class="icon-home">🏠</i>
                <span>首页</span>
            </div>
            <div class="nav-item" :class="{ 'active': activeTab === 'collection' }" @click="navigateTo('collection')">
                <i class="icon-collection">❤️</i>
                <span>收藏</span>
            </div>
            <div class="nav-item" :class="{ 'active': activeTab === 'community' }" @click="navigateTo('community')">
                <i class="icon-community">👥</i>
                <span>社区</span>
            </div>
        </footer>

        <!-- 诗词详情弹窗 -->
        <div v-if="showDetail" class="poem-detail-modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>{{ currentPoem.title }}</h3>
                    <span class="close-btn" @click="closeDetail">×</span>
                </div>
                <div class="modal-body">
                    <div class="poem-author-info">{{ currentPoem.dynasty }} · {{ currentPoem.author }}</div>
                    <div class="poem-content">{{ currentPoem.content }}</div>
                    <div class="poem-interpretation">
                        <h4>诗词解读</h4>
                        <p>{{ currentPoem.interpretation }}</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn-collect" @click="toggleCollect(currentPoem)">
                        {{ isCollected(currentPoem) ? '取消收藏' : '收藏' }}
                    </button>
                    <button class="btn-share" @click="sharePoem(currentPoem)">分享</button>
                </div>
            </div>
        </div>

        <!-- 收藏页面 -->
        <div v-if="showCollections" class="collections-page">
            <div class="collections-header">
                <h2>我的收藏</h2>
                <span class="close-btn" @click="closeCollections">×</span>
            </div>
            <div class="collections-content">
                <div v-if="collections.length === 0" class="no-collections">
                    <p>暂无收藏诗词</p>
                </div>
                <div v-else class="collection-list">
                    <div v-for="(poem, index) in uniqueCollections" :key="index" class="collection-item"
                        @click="showPoemDetail(getFullPoemById(poem.id))">
                        <h3 class="collection-title">{{ poem.title }}</h3>
                        <div class="collection-author">{{ poem.dynasty }} · {{ poem.author }}</div>
                        <button class="btn-remove" @click.stop="toggleCollect(poem)">取消收藏</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 社区页面 -->
        <div v-if="showCommunity" class="community-page">
            <div class="community-header">
                <h2>社区</h2>
                <span class="close-btn" @click="closeCommunity">×</span>
            </div>
            <div class="community-content">
                <div class="community-message">
                    <p>社区功能还未开放，敬请期待。</p>
                </div>
            </div>
        </div>

        <!-- 加载遮罩 -->
        <div v-if="isLoading" class="loading-mask">
            <div class="loading-spinner"></div>
        </div>

        <!-- 提示消息 -->
        <div v-if="toast.show" class="toast" :class="toast.type">
            {{ toast.message }}
        </div>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    name: 'ShigeApp',
    data() {
        return {
            // 深色模式状态
            isDarkMode: false,
            // 搜索框输入内容
            searchQuery: '',
            // 推荐诗词列表
            recommendedPoems: [],
            // 当前激活的导航标签页
            activeTab: 'home',
            // 是否显示收藏页面
            showCollections: false,
            // 是否显示社区页面
            showCommunity: false,
            // 是否显示诗人详情弹窗
            showPoetDetailModal: false,
            // 当前选中的诗人信息
            currentPoet: {},
            // 诗词主题分类列表
            themeCategories: [
                { name: '山水', icon: '🏞️' },
                { name: '思乡', icon: '🏠' },
                { name: '爱情', icon: '❤️' },
                { name: '边塞', icon: '🏇' },
                { name: '咏物', icon: '🌸' },
                { name: '友情', icon: '🤝' }
            ],
            // 推荐诗人列表
            recommendedPoets: [{
                name: '李白',
                dynasty: '唐代',
                avatar: '李',
                description: '诗仙，浪漫主义诗人，代表作《将进酒》《行路难》等',
                famousWorks: ['将进酒', '行路难', '静夜思'],
                evaluation: '豪放不羁，想象丰富，诗风清新飘逸',
                wikiLink: 'baidu.com'
            },
            {
                name: '杜甫',
                dynasty: '唐代',
                avatar: '杜',
                description: '诗圣，现实主义诗人，代表作《春望》《茅屋为秋风所破歌》等',
                famousWorks: ['春望', '茅屋为秋风所破歌', '登高'],
                evaluation: '忧国忧民，诗风沉郁顿挫，内容丰富',
                wikiLink: 'baidu.com'
            },
            {
                name: '苏轼',
                dynasty: '宋代',
                avatar: '苏',
                description: '豪放派代表，文学家、书画家，代表作《念奴娇·赤壁怀古》',
                famousWorks: ['念奴娇·赤壁怀古', '水调歌头·明月几时有', '定风波'],
                evaluation: '豪放旷达，才华横溢，诗文书画皆精',
                wikiLink: 'baidu.com'
            }
            ],
            showDetail: false,
            currentPoem: {},
            isLoading: false,
            toast: {
                show: false,
                message: '',
                type: 'info'
            },
            collections: [],
            // 示例数据
            samplePoems: [
                {
                    id: 1,
                    title: '静夜思',
                    author: '李白',
                    dynasty: '唐代',
                    content: '床前明月光，疑是地上霜。\n举头望明月，低头思故乡。',
                    excerpt: '床前明月光，疑是地上霜...',
                    interpretation: '这首诗描绘了诗人在月夜思念故乡的情景。诗人通过明月这一意象，表达了对故乡的深切思念之情。诗中的"明月光"与"地上霜"形成对比，突出了夜的寂静与诗人内心的孤独。'
                },
                {
                    id: 2,
                    title: '登鹳雀楼',
                    author: '王之涣',
                    dynasty: '唐代',
                    content: '白日依山尽，黄河入海流。\n欲穷千里目，更上一层楼。',
                    excerpt: '白日依山尽，黄河入海流...',
                    interpretation: '这首诗描绘了诗人登上鹳雀楼后看到的壮丽景色，以及由此产生的豁达情怀。诗中"白日依山尽，黄河入海流"描绘了广阔的自然景观，"欲穷千里目，更上一层楼"则表达了诗人追求更高境界的进取精神。'
                },
                {
                    id: 3,
                    title: '春晓',
                    author: '孟浩然',
                    dynasty: '唐代',
                    content: '春眠不觉晓，处处闻啼鸟。\n夜来风雨声，花落知多少。',
                    excerpt: '春眠不觉晓，处处闻啼鸟...',
                    interpretation: '这首诗描绘了一个春天早晨的宁静与美好。诗人被鸟叫声唤醒，回忆起昨夜的风雨，担心花朵凋落的情景。诗中充满了对春天的喜爱和对美好事物易逝的惋惜之情。'
                }
            ],
            llmResult: {
                "id": "0196f5bb06e08d6e9b328a5793e1f3b7",
                "object": "chat.completion",
                "created": 1747879397,
                "model": "deepseek-ai/DeepSeek-R1-Distill-Qwen-32B",
                "choices": [
                    {
                        "index": 0,
                        "message": {
                            "role": "assistant",
                            "content": "\n\n```json\n{\n  \"title\": \"赋得古原草送别\",\n  \"author\": \"白居易\",\n  \"dynasty\": \"唐\",\n  \"content\": \"离离原上草，一岁一枯荣。\\n野火烧不尽，春风吹又生。\\n远芳侵古道，晴翠接荒城。\\n又送王孙去，萋萋满别情。\",\n  \"excerpt\": \"离离原上草，一岁一枯荣。\",\n  \"interpretation\": \"这首诗以古原草为题材，通过对草的生长与衰败的描绘，表达了离别时的深情。诗中'野火烧不尽，春风吹又生'寓意草的顽强生命力，也象征着离别后的重逢之希望，情感真挚动人。\"\n}\n```",
                            "reasoning_content": "好的，我现在需要处理用户的查询。用户希望根据“草”这个关键词，找到一首相关的中国古诗词，并返回特定格式的JSON。首先，我要确定用户的需求是什么。看起来用户可能是一位对中国古典诗词感兴趣的人，或者需要在学习中使用这些资料。用户可能希望得到一首著名的诗，这样他们可以获得更多的信息和分析。\n\n接下来，我应该考虑哪些关于“草”的古诗词比较合适。白居易的《赋得古原草送别》是一个很好的选择，因为它不仅以草为主题，还表达了离别的情感，内容丰富且广为人知。这样用户在获取诗词的同时，还能理解其背后的意义，符合用户可能希望深入了解的需求。\n\n然后，我需要确保返回的JSON格式符合用户的要求，包括标题、作者、朝代、内容、节选和解读。这些信息要准确无误，特别是解读部分，需要简明扼要地概述诗的主题和情感，大约100字左右。\n\n在整理信息时，我要仔细检查每一部分的内容是否正确。例如，确认白居易的朝代是唐朝，诗的标题和内容是否正确无误。节选部分要选取前两句，这样用户可以快速了解诗的开头。解读部分需要概括诗中的自然景象和离别之情，以及草的顽强生命力，这样用户能够理解诗的深层含义。\n\n最后，我要确保整个JSON格式正确，没有语法错误，这样用户在解析时不会遇到问题。同时，保持回复的自然和专业，符合用户对中国古典诗词专家的期待。\n"
                        },
                        "finish_reason": "stop"
                    }
                ],
                "usage": {
                    "prompt_tokens": 116,
                    "completion_tokens": 497,
                    "total_tokens": 613,
                    "completion_tokens_details": {
                        "reasoning_tokens": 323
                    }
                },
                "system_fingerprint": ""
            },
            llmResult2: {
                "id": "0196f5fae948a6f782b7bd1a43a7162e",
                "object": "chat.completion",
                "created": 1747883583,
                "model": "deepseek-ai/DeepSeek-R1-Distill-Qwen-32B",
                "choices": [
                    {
                        "index": 0,
                        "message": {
                            "role": "assistant",
                            "content": "\n\n```json\n[\n  {\n    \"title\": \"静夜思\",\n    \"author\": \"李白\",\n    \"dynasty\": \"唐\",\n    \"content\": \"床前明月光，疑是地上霜。\\n举头望明月，低头思故乡。\",\n    \"excerpt\": \"床前明月光，疑是地上霜。\",\n    \"interpretation\": \"这首诗描绘了诗人在寂静的夜晚，因月光而引发的思乡之情。前两句通过生动的比喻，营造出一种清冷的氛围；后两句则直接表达了诗人对故乡的深深思念，语言简练而意境深远。\"\n  },\n  {\n    \"title\": \"声声慢·寻寻觅觅\",\n    \"author\": \"李清照\",\n    \"dynasty\": \"宋\",\n    \"content\": \"寻寻觅觅，冷冷清清，凄凄惨惨戚戚。\\n乍暖还寒时候，最难将息。\\n三杯两盏淡酒，怎敌他、晚来风急！\\n雁过也，正伤心，却是旧时相识。\\n满地黄花堆积，憔悴损，如今有谁堪摘？\\n守着窗儿，独自怎生得黑！\\n梧桐更兼细雨，到黄昏、点点滴滴。\\n这次第，怎一个愁字了得！\",\n    \"excerpt\": \"寻寻觅觅，冷冷清清，凄凄惨惨戚戚。\",\n    \"interpretation\": \"这首词通过细腻的描写，表达了词人在国破家亡后的孤寂与哀愁。全词情感真挚，借景抒情，层层递进，展现了李清照独特的艺术风格和深刻的情感世界。\"\n  },\n  {\n    \"title\": \"山中送别\",\n    \"author\": \"王维\",\n    \"dynasty\": \"唐\",\n    \"content\": \"山中相送罢，日暮掩柴扉。\\n春草明年绿，王孙归不归？\",\n    \"excerpt\": \"山中相送罢，日暮掩柴扉。\",\n    \"interpretation\": \"这首诗以简洁的语言，表达了送别后的深情与期待。诗中通过对自然景物的描绘，寄寓了对友人的思念和对未来的希望，展现了王维诗中的自然与人文交融之美。\"\n  }\n]\n```",
                            "reasoning_content": "好，用户需要我生成三首中国古诗词推荐，并且要求返回格式为JSON数组。首先，我得确保选择的诗词具有代表性，涵盖不同的朝代和风格。\n\n我想到了李白的《静夜思》，这是唐代非常经典的一首诗，内容简洁而意境深远，适合推荐。\n\n接下来，选择李清照的《声声慢·寻寻觅觅》，这不仅是宋代词的代表作之一，而且情感丰富，能很好地展示宋词的特点。\n\n最后，王维的《山中送别》作为唐代的另一首佳作，表达了送别时的深情，适合多样性的推荐。\n\n然后，我需要按照要求的JSON格式来组织每首诗的信息，包括标题、作者、朝代、完整内容、节选以及解读。\n\n在解读部分，我尽量控制在100字左右，简明扼要地说明每首诗的意境和艺术特色。\n\n完成这三首诗的整理后，我检查了一遍格式是否正确，确保没有遗漏任何信息。\n\n最后，将整个JSON数组返回给用户，满足他们的需求。\n"
                        },
                        "finish_reason": "stop"
                    }
                ],
                "usage": {
                    "prompt_tokens": 114,
                    "completion_tokens": 731,
                    "total_tokens": 845,
                    "completion_tokens_details": {
                        "reasoning_tokens": 230
                    }
                },
                "system_fingerprint": ""
            }
        };
    },
    created() {
        // 加载用户主题偏好
        this.loadThemePreference();

        // 加载收藏列表
        this.loadCollections();

        // 初始化推荐诗词（使用示例数据）
        this.initializeRecommendedPoems();

        // 设置默认选中首页
        this.activeTab = 'home';
    },
    computed: {
        // 根据标题去重的推荐诗词
        uniqueRecommendedPoems() {
            const uniqueMap = new Map();
            this.recommendedPoems.forEach(poem => {
                if (!uniqueMap.has(poem.title)) {
                    uniqueMap.set(poem.title, poem);
                }
            });
            return Array.from(uniqueMap.values());
        },

        // 根据标题去重的收藏诗词
        uniqueCollections() {
            const uniqueMap = new Map();
            this.collections.forEach(poem => {
                if (!uniqueMap.has(poem.title)) {
                    uniqueMap.set(poem.title, poem);
                }
            });
            return Array.from(uniqueMap.values());
        }
    },
    methods: {
        // 初始化推荐诗词
        initializeRecommendedPoems() {
            const storedElements = localStorage.getItem('shige-poemArray');
            if (storedElements) {
                this.recommendedPoems = JSON.parse(storedElements);
            } else {
                // 使用示例数据
                this.recommendedPoems = this.samplePoems;
            }
        },

        // 切换主题模式
        toggleTheme() {
            this.isDarkMode = !this.isDarkMode;
            localStorage.setItem('shige-theme-dark', this.isDarkMode);
        },

        // 加载主题偏好
        loadThemePreference() {
            const darkMode = localStorage.getItem('shige-theme-dark');
            if (darkMode !== null) {
                this.isDarkMode = darkMode === 'true';
            } else {
                // 默认根据系统偏好设置
                const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
                this.isDarkMode = prefersDark;
            }
        },

        // 使用AI查询诗词
        async generatePoemWithAI(prompt) {
            this.isLoading = true;
            try {
                const response = await axios.post('https://api.siliconflow.cn/v1/chat/completions', {
                    model: 'deepseek-ai/DeepSeek-R1-Distill-Qwen-32B',
                    messages: [
                        {
                            role: 'system',
                            content: '你是一位中国古典诗词专家，精通唐诗宋词。请根据用户的要求查询或解析古诗词。'
                        },
                        {
                            role: 'user',
                            content: prompt
                        }
                    ],
                    stream: false,
                    max_tokens: 2048,
                    temperature: 0.7
                }, {
                    headers: {
                        Authorization: 'Bearer ' + process.env.VUE_APP_API_KEY,
                        'Content-Type': 'application/json'
                    }
                });
                let content = response.data.choices[0].message.content;
                return content
                // 尝试提取JSON部分（处理可能包含的markdown格式）
            } catch (error) {
                console.error('AI生成诗词失败:', error);
                this.showToast('AI服务暂时不可用，使用示例数据', 'warning');
                return null;
            } finally {
                this.isLoading = false;
            }
        },

        dealContentJson(content) {
            const jsonMatch = content.match(/```json\s*([\s\S]*?)\s*```/) ||
                content.match(/\{[\s\S]*\}/);

            if (jsonMatch) {
                try {
                    content = JSON.parse(jsonMatch[1] || jsonMatch[0]);
                } catch (e) {
                    console.error('JSON解析错误:', e);
                    throw new Error('返回数据格式错误');
                }
            } else {
                throw new Error('未找到有效的JSON数据');
            }

            return content;
        },
        dealContentJsonArray(content) {
            const jsonMatch = content.match(/```json\s*([\s\S]*?)\s*```/) ||
                content.match(/\{[\s\S]*\}/);

            if (jsonMatch) {
                try {
                    content = JSON.parse(jsonMatch[1] || jsonMatch[0]);
                } catch (e) {
                    console.error('JSON解析错误:', e);
                    throw new Error('返回数据格式错误');
                }
            } else {
                throw new Error('未找到有效的JSON数据');
            }

            return content;
        },
        mockData1() {
            const response = this.llmResult
            let content = response.choices[0].message.content;
            const jsonMatch = content.match(/```json\s*([\s\S]*?)\s*```/) ||
                content.match(/\{[\s\S]*\}/);

            if (jsonMatch) {
                try {
                    content = JSON.parse(jsonMatch[1] || jsonMatch[0]);
                } catch (e) {
                    console.error('JSON解析错误:', e);
                    throw new Error('返回数据格式错误');
                }
            } else {
                throw new Error('未找到有效的JSON数据');
            }

            return content;
        },
        mockData2() {
            const response = this.llmResult2
            let content = response.choices[0].message.content;
            const jsonMatch = content.match(/```json\s*([\s\S]*?)\s*```/) ||
                content.match(/\{[\s\S]*\}/);

            if (jsonMatch) {
                try {
                    content = JSON.parse(jsonMatch[1] || jsonMatch[0]);
                } catch (e) {
                    console.error('JSON解析错误:', e);
                    throw new Error('返回数据格式错误');
                }
            } else {
                throw new Error('未找到有效的JSON数据');
            }

            return content;
        },



        // 搜索诗词
        async searchPoems() {
            if (!this.searchQuery.trim()) {
                this.showToast('请输入搜索内容', 'warning');
                return;
            }

            this.isLoading = true;

            // 先在示例数据中搜索
            const localResults = this.samplePoems.filter(poem =>
                poem.title.includes(this.searchQuery) ||
                poem.author.includes(this.searchQuery) ||
                poem.content.includes(this.searchQuery)
            );

            if (localResults.length > 0) {
                this.recommendedPoems = localResults;
                this.isLoading = false;
                return;
            }

            // 本地没有结果，调用AI生成
            try {
                const prompt = `请根据"${this.searchQuery}"这个关键词，查询一首相关的中国古诗词。返回格式为JSON：
        {
          "title": "诗词标题",
          "author": "作者名",
          "dynasty": "朝代",
          "content": "完整诗词内容",
          "excerpt": "诗词节选（前两句）",
          "interpretation": "诗词解读（100字左右）"
        }`;

                let poemData = await this.generatePoemWithAI(prompt);
                poemData = this.dealContentJson(poemData);
                if (poemData) {
                    try {
                        // 解析JSON结果
                        // const poemData = JSON.parse(result);
                        const newPoem = {
                            id: Date.now(),
                            ...poemData
                        };
                        localStorage.setItem('shige-poemArray', JSON.stringify([newPoem, ...this.recommendedPoems.slice(0,this.recommendedPoems.length)]));

                        this.recommendedPoems = [newPoem];
                    } catch (e) {
                        console.error('解析AI返回结果失败:', e);
                        this.showToast('解析诗词数据失败', 'error');
                    }
                } else {
                    this.showToast('未找到相关诗词', 'info');
                }
            } finally {
                this.isLoading = false;
            }
        },

        // 生成诗词解读
        async generatePoemInterpretation(poem) {
            if (poem.interpretation) return poem.interpretation;

            this.isLoading = true;

            try {
                const prompt = `请对这首诗进行解读（100字左右）：
        标题：${poem.title}
        作者：${poem.author}
        朝代：${poem.dynasty}
        内容：${poem.content}`;

                const result = await this.generatePoemWithAI(prompt);

                if (result) {
                    // 更新诗词解读
                    poem.interpretation = result;
                    return result;
                } else {
                    return '暂无解读';
                }
            } catch (error) {
                console.error('生成诗词解读失败:', error);
                return '暂无解读';
            } finally {
                this.isLoading = false;
            }
        },

        // 显示诗词详情
        async showPoemDetail(poem) {
            this.currentPoem = poem;

            // 如果没有解读，生成一个
            if (!poem.interpretation) {
                poem.interpretation = await this.generatePoemInterpretation(poem);
            }

            this.showDetail = true;
        },

        // 关闭诗词详情
        closeDetail() {
            this.showDetail = false;
        },

        // 根据主题查询诗词
        async generatePoemByTheme(theme) {
            this.isLoading = true;

            try {
                const prompt = `请查询一首与"${theme.name}"主题相关的中国古诗词。返回格式为JSON：
        {
          "title": "诗词标题",
          "author": "作者名",
          "dynasty": "朝代",
          "content": "完整诗词内容",
          "excerpt": "诗词节选（前两句）",
          "interpretation": "诗词解读（100字左右）"
        }`;

                const result = await this.generatePoemWithAI(prompt);
                const poemData = this.dealContentJsonArray(result);
                if (poemData) {
                    try {
                        // 解析JSON结果
                        const newPoem = {
                            id: Date.now(),
                            ...poemData
                        };

                        // 添加到推荐列表
                        this.recommendedPoems = [newPoem, ...this.recommendedPoems.slice(0, 2)];
                        localStorage.setItem('shige-poemArray', JSON.stringify(this.recommendedPoems));
                        this.showToast(`已生成"${theme.name}"主题诗词`, 'success');
                        this.showPoemDetail(newPoem)
                    } catch (e) {
                        console.error('解析AI返回结果失败:', e);
                        this.showToast('解析诗词数据失败', 'error');
                    }
                }
            } finally {
                this.isLoading = false;
            }
        },

        // 选择主题
        async selectTheme(theme) {
            this.showToast(`已选择"${theme.name}"主题`, 'info');
            await this.generatePoemByTheme(theme);
        },

        // 显示诗人详情
        showPoetDetail(poet) {
            this.currentPoet = poet;
            this.showPoetDetailModal = true;
        },

        // 关闭诗人详情
        closePoetDetail() {
            this.showPoetDetailModal = false;
        },

        // 导航到其他页面
        navigateTo(page) {
            this.activeTab = page;

            if (page === 'collection') {
                this.showCollections = true;
                this.showCommunity = false;
                this.showToast('查看收藏诗词', 'info');
            } else if (page === 'community') {
                this.showCommunity = true;
                this.showCollections = false;
                this.showToast('社区功能还未开放，敬请期待', 'info');
            } else {
                // 首页
                this.showCollections = false;
                this.showCommunity = false;
            }
        },

        // 关闭收藏页面
        closeCollections() {
            this.showCollections = false;
            this.activeTab = 'home';
        },

        // 关闭社区页面
        closeCommunity() {
            this.showCommunity = false;
            this.activeTab = 'home';
        },

        // 根据ID获取完整诗词信息
        getFullPoemById(id) {
            // 先从推荐诗词中查找
            let poem = this.recommendedPoems.find(p => p.id === id);

            // 如果没找到，可能是示例数据
            if (!poem) {
                poem = this.samplePoems.find(p => p.id === id);
            }

            return poem || this.collections.find(p => p.id === id);
        },

        // 刷新诗人推荐
        async refreshPoetRecommendations() {
            this.isLoading = true;

            try {
                const prompt = `请生成3位中国古代著名诗人的信息，包括姓名、朝代、代表作品、评价。返回格式为JSON数组：
        [
          {
            "name": "诗人姓名",
            "dynasty": "朝代",
            "avatar": "姓氏第一个字",
            "description": "简短描述（30字左右）",
            "famousWorks": ["代表作1", "代表作2", "代表作3"],
            "evaluation": "对诗人的评价（30字左右）",
            "wikiLink": "baidu.com"
          }
        ]`;

                let result = await this.generatePoemWithAI(prompt);
                result = this.dealContentJsonArray(result)
                if (result && Array.isArray(result)) {
                    // 确保每个诗人都有avatar字段
                    const newPoets = result.map(poet => ({
                        ...poet,
                        avatar: poet.avatar || poet.name.charAt(0),
                        wikiLink: poet.wikiLink || "baidu.com"
                    }));

                    this.recommendedPoets = newPoets;
                    this.showToast('已更新诗人推荐', 'success');
                } else {
                    this.showToast('生成诗人数据失败', 'error');
                }
            } catch (error) {
                console.error('刷新诗人推荐失败:', error);
                this.showToast('刷新诗人推荐失败', 'error');
            } finally {
                this.isLoading = false;
            }
        },

        // 刷新每日推荐
        async refreshDailyRecommendations() {
            this.isLoading = true;

            try {
                const prompt = `请生成3首中国古诗词推荐。返回格式为JSON数组：
        [
          {
            "title": "诗词标题",
            "author": "作者名",
            "dynasty": "朝代",
            "content": "完整诗词内容",
            "excerpt": "诗词节选（前两句）",
            "interpretation": "诗词解读（100字左右）"
          }
        ]`;
                let result = await this.generatePoemWithAI(prompt);
                result = this.dealContentJsonArray(result)
                //let result = this.mockData2()
                // console.log(result)
                if (result && Array.isArray(result)) {
                    // 添加ID
                    const newPoems = result.map(poem => ({
                        id: Date.now() + Math.floor(Math.random() * 1000),
                        ...poem
                    }));

                    this.recommendedPoems = newPoems;
                    this.showToast('已更新每日推荐', 'success');
                } else {
                    this.showToast('生成推荐诗词失败', 'error');
                }
            } catch (error) {
                console.error('刷新每日推荐失败:', error);
                this.showToast('刷新每日推荐失败', 'error');
            } finally {
                this.isLoading = false;
            }
        },

        // 显示提示消息
        showToast(message, type = 'info') {
            this.toast = {
                show: true,
                message,
                type
            };

            // 3秒后自动关闭
            setTimeout(() => {
                this.toast.show = false;
            }, 3000);
        },

        // 加载收藏列表
        loadCollections() {
            const collections = localStorage.getItem('shige-collections');
            if (collections) {
                try {
                    this.collections = JSON.parse(collections);
                } catch (e) {
                    this.collections = [];
                }
            }
        },

        // 检查是否已收藏
        isCollected(poem) {
            return this.collections.some(item => item.id === poem.id);
        },

        // 切换收藏状态
        toggleCollect(poem) {
            const index = this.collections.findIndex(item => item.id === poem.id);

            if (index >= 0) {
                // 取消收藏
                this.collections.splice(index, 1);
                this.showToast('已取消收藏', 'info');
            } else {
                // 添加收藏
                this.collections.push({
                    id: poem.id,
                    title: poem.title,
                    author: poem.author,
                    dynasty: poem.dynasty
                });
                this.showToast('收藏成功', 'success');
            }

            // 保存到本地存储
            localStorage.setItem('shige-collections', JSON.stringify(this.collections));
        },

        // 分享诗词
        sharePoem(poem) {
            // 模拟分享功能
            const shareText = `${poem.title} - ${poem.author}\n${poem.content}`;

            // 检查是否支持原生分享API
            if (navigator.share) {
                navigator.share({
                    title: `${poem.title} - ${poem.author}`,
                    text: shareText
                }).catch(() => {
                    this.showToast('分享功能暂不可用', 'warning');
                });
            } else {
                // 复制到剪贴板
                this.copyToClipboard(shareText);
                this.showToast('诗词内容已复制，可粘贴分享', 'success');
            }
        },

        // 复制到剪贴板
        copyToClipboard(text) {
            const textarea = document.createElement('textarea');
            textarea.value = text;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('copy');
            document.body.removeChild(textarea);
        },
            // 处理搜索输入
    handleSearchInput() {
      if (!this.searchQuery.trim()) {
        // 当搜索框清空时，恢复默认列表
        const savedStars = localStorage.getItem('shige-poemArray');
        if (savedStars) {
          this.recommendedPoems = JSON.parse(savedStars);
        } else {
          this.recommendedPoems = this.samplePoems;
        }
      }
    },
    }
};
</script>

<style scoped>
/* 基础样式 */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.shige-container {
    font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
    color: #333;
    background-color: #f9f5e9;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    transition: all 0.3s ease;
}

/* 深色模式 */
.dark-mode {
    background-color: #1c1c1e;
    color: #e0e0e0;
}

.dark-mode .header {
    background-color: #2c2c2e;
}

.dark-mode .section {
    background-color: #2c2c2e;
}

.dark-mode .poem-card,
.dark-mode .theme-item,
.dark-mode .poet-item {
    background-color: #3a3a3c;
}

.dark-mode .footer {
    background-color: #2c2c2e;
}

.dark-mode .modal-content {
    background-color: #2c2c2e;
}

/* 顶部导航栏 */
.header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px;
    background-color: #fff;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    position: sticky;
    top: 0;
    z-index: 100;
}

.logo {
    font-size: 20px;
    font-weight: bold;
    color: #8a2be2;
    font-family: "STKaiti", "KaiTi", serif;
}

.search-box {
    display: flex;
    flex: 1;
    margin: 0 15px;
    position: relative;
}

.search-box input {
    width: 100%;
    padding: 8px 35px 8px 15px;
    border: 1px solid #ddd;
    border-radius: 20px;
    font-size: 14px;
    background-color: #f5f5f5;
}

.dark-mode .search-box input {
    background-color: #3a3a3c;
    border-color: #555;
    color: #e0e0e0;
}

.search-btn {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    background: none;
    border: none;
    cursor: pointer;
    font-size: 16px;
}

.theme-toggle {
    font-size: 20px;
    cursor: pointer;
}

/* 主内容区 */
.main-content {
    flex: 1;
    padding: 15px;
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.section {
    background-color: #fff;
    border-radius: 10px;
    padding: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.section-title {
    font-size: 18px;
    margin-bottom: 15px;
    color: #8a2be2;
    font-family: "STKaiti", "KaiTi", serif;
    position: relative;
    padding-left: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.section-title::before {
    content: "";
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 18px;
    background-color: #8a2be2;
    border-radius: 2px;
}

.refresh-icon {
    font-size: 16px;
    cursor: pointer;
    margin-left: auto;
    transition: transform 0.3s ease;
}

.refresh-icon:hover {
    transform: rotate(90deg);
}

/* 诗词卡片 */
.poem-cards {
    display: flex;
    overflow-x: auto;
    gap: 15px;
    padding: 5px 0;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none;
    /* Firefox */
}

.poem-cards::-webkit-scrollbar {
    display: none;
    /* Chrome, Safari, Edge */
}

.poem-card {
    flex: 0 0 250px;
    background-color: #f9f9f9;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    cursor: pointer;
    transition: transform 0.2s ease;
}

.poem-card:hover {
    transform: translateY(-3px);
}

.poem-title {
    font-size: 16px;
    margin-bottom: 8px;
    font-family: "STKaiti", "KaiTi", serif;
}

.poem-author {
    font-size: 12px;
    color: #888;
    margin-bottom: 10px;
}

.dark-mode .poem-author {
    color: #aaa;
}

.poem-excerpt {
    font-size: 14px;
    line-height: 1.5;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* 主题分类 */
.theme-list {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
}

.theme-item {
    background-color: #f9f9f9;
    border-radius: 8px;
    padding: 15px 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    transition: transform 0.2s ease;
}

.theme-item:hover {
    transform: scale(1.05);
}

.theme-icon {
    font-size: 24px;
    margin-bottom: 8px;
}

.theme-name {
    font-size: 14px;
    font-family: "STKaiti", "KaiTi", serif;
}

/* 诗人推荐 */
.poet-list {
    display: flex;
    overflow-x: auto;
    gap: 15px;
    padding: 5px 0;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none;
}

.poet-list::-webkit-scrollbar {
    display: none;
}

.poet-item {
    flex: 0 0 auto;
    display: flex;
    align-items: center;
    background-color: #f9f9f9;
    border-radius: 8px;
    padding: 10px;
    cursor: pointer;
    transition: transform 0.2s ease;
}

.poet-item:hover {
    transform: translateY(-3px);
}

.poet-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #8a2be2;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    margin-right: 10px;
    font-family: "STKaiti", "KaiTi", serif;
}

.poet-name {
    font-size: 16px;
    margin-bottom: 4px;
    font-family: "STKaiti", "KaiTi", serif;
}

.poet-dynasty {
    font-size: 12px;
    color: #888;
}

.dark-mode .poet-dynasty {
    color: #aaa;
}

/* 底部导航 */
.footer {
    display: flex;
    justify-content: space-around;
    padding: 10px 0;
    background-color: #fff;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.nav-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 5px 0;
    cursor: pointer;
    position: relative;
}

.nav-item.active {
    color: #8a2be2;
}

.nav-item.active::after {
    content: "";
    position: absolute;
    bottom: -5px;
    left: 50%;
    transform: translateX(-50%);
    width: 20px;
    height: 3px;
    background-color: #8a2be2;
    border-radius: 2px;
}

.nav-item i {
    font-size: 20px;
    margin-bottom: 4px;
}

.nav-item span {
    font-size: 12px;
}

/* 诗词详情弹窗 */
.poem-detail-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    animation: fadeIn 0.3s ease;
}

/* 收藏页面 */
.collections-page {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #f9f5e9;
    z-index: 900;
    display: flex;
    flex-direction: column;
    animation: slideIn 0.3s ease;
}

.dark-mode .collections-page {
    background-color: #1c1c1e;
}

.collections-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background-color: #fff;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.dark-mode .collections-header {
    background-color: #2c2c2e;
}

.collections-content {
    flex: 1;
    padding: 15px;
    overflow-y: auto;
}

.no-collections {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200px;
    font-size: 16px;
    color: #888;
}

.collection-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 15px;
}

.collection-item {
    background-color: #fff;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    cursor: pointer;
    transition: transform 0.2s ease;
    position: relative;
}

.dark-mode .collection-item {
    background-color: #2c2c2e;
}

.collection-item:hover {
    transform: translateY(-3px);
}

.collection-title {
    font-size: 16px;
    margin-bottom: 8px;
    font-family: "STKaiti", "KaiTi", serif;
}

.collection-author {
    font-size: 12px;
    color: #888;
    margin-bottom: 30px;
}

.dark-mode .collection-author {
    color: #aaa;
}

.btn-remove {
    position: absolute;
    bottom: 15px;
    right: 15px;
    padding: 5px 10px;
    border: none;
    border-radius: 15px;
    background-color: #f0f0f0;
    color: #333;
    font-size: 12px;
    cursor: pointer;
    transition: background-color 0.2s ease;
}

.dark-mode .btn-remove {
    background-color: #3a3a3c;
    color: #e0e0e0;
}

.btn-remove:hover {
    background-color: #ff6b6b;
    color: white;
}

/* 诗人详情弹窗 */
.poet-detail-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    animation: fadeIn 0.3s ease;
}

.poet-detail-info {
    display: flex;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
}

.dark-mode .poet-detail-info {
    border-color: #444;
}

.poet-detail-avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background-color: #8a2be2;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    margin-right: 15px;
    font-family: "STKaiti", "KaiTi", serif;
}

.poet-detail-meta {
    flex: 1;
}

.poet-detail-dynasty {
    font-size: 14px;
    color: #888;
    margin-bottom: 8px;
}

.dark-mode .poet-detail-dynasty {
    color: #aaa;
}

.poet-detail-description {
    font-size: 16px;
    line-height: 1.6;
}

.poet-detail-section {
    margin-bottom: 15px;
}

.poet-detail-section h4 {
    font-size: 16px;
    margin-bottom: 10px;
    color: #8a2be2;
    font-family: "STKaiti", "KaiTi", serif;
}

.poet-works {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.poet-work-item {
    background-color: #f0f0f0;
    padding: 5px 10px;
    border-radius: 15px;
    font-size: 14px;
}

.dark-mode .poet-work-item {
    background-color: #3a3a3c;
}

.wiki-link {
    display: inline-block;
    padding: 8px 15px;
    background-color: #8a2be2;
    color: white;
    border-radius: 20px;
    text-decoration: none;
    font-size: 14px;
    transition: background-color 0.2s ease;
}

.wiki-link:hover {
    background-color: #7a1bd2;
}

/* 社区页面 */
.community-page {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #f9f5e9;
    z-index: 900;
    display: flex;
    flex-direction: column;
    animation: slideIn 0.3s ease;
}

.dark-mode .community-page {
    background-color: #1c1c1e;
}

.community-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background-color: #fff;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.dark-mode .community-header {
    background-color: #2c2c2e;
}

.community-content {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
}

.community-message {
    text-align: center;
    padding: 30px;
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    max-width: 80%;
}

.dark-mode .community-message {
    background-color: #2c2c2e;
}

.community-message p {
    font-size: 18px;
    color: #8a2be2;
    font-family: "STKaiti", "KaiTi", serif;
}

@keyframes slideIn {
    from {
        transform: translateY(100%);
    }

    to {
        transform: translateY(0);
    }
}

.modal-content {
    width: 90%;
    max-width: 500px;
    max-height: 80vh;
    background-color: #fff;
    border-radius: 10px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.modal-header {
    padding: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #eee;
}

.dark-mode .modal-header {
    border-color: #444;
}

.modal-header h3 {
    font-size: 18px;
    font-family: "STKaiti", "KaiTi", serif;
}

.close-btn {
    font-size: 24px;
    cursor: pointer;
}

.modal-body {
    padding: 15px;
    overflow-y: auto;
    flex: 1;
}

.poem-author-info {
    font-size: 14px;
    color: #888;
    margin-bottom: 15px;
}

.dark-mode .poem-author-info {
    color: #aaa;
}

.poem-content {
    font-size: 16px;
    line-height: 1.8;
    white-space: pre-line;
    margin-bottom: 20px;
    font-family: "STKaiti", "KaiTi", serif;
}

.poem-interpretation {
    background-color: #f9f9f9;
    padding: 15px;
    border-radius: 8px;
}

.dark-mode .poem-interpretation {
    background-color: #3a3a3c;
}

.poem-interpretation h4 {
    font-size: 16px;
    margin-bottom: 10px;
    color: #8a2be2;
}

.poem-interpretation p {
    font-size: 14px;
    line-height: 1.6;
}

.modal-footer {
    padding: 15px;
    display: flex;
    justify-content: space-between;
    border-top: 1px solid #eee;
}

.dark-mode .modal-footer {
    border-color: #444;
}

.modal-footer button {
    padding: 8px 20px;
    border: none;
    border-radius: 20px;
    font-size: 14px;
    cursor: pointer;
    transition: background-color 0.2s ease;
}

.btn-collect {
    background-color: #8a2be2;
    color: white;
}

.btn-collect:hover {
    background-color: #7a1bd2;
}

.btn-share {
    background-color: #f0f0f0;
    color: #333;
}

.dark-mode .btn-share {
    background-color: #3a3a3c;
    color: #e0e0e0;
}

.btn-share:hover {
    background-color: #e0e0e0;
}

.dark-mode .btn-share:hover {
    background-color: #444;
}

/* 加载遮罩 */
.loading-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2000;
}

.loading-spinner {
    width: 50px;
    height: 50px;
    border: 5px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    border-top-color: #8a2be2;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

/* 提示消息 */
.toast {
    position: fixed;
    bottom: 80px;
    left: 50%;
    transform: translateX(-50%);
    padding: 10px 20px;
    border-radius: 20px;
    color: white;
    font-size: 14px;
    z-index: 3000;
    animation: fadeIn 0.3s ease;
}

.toast.info {
    background-color: rgba(33, 150, 243, 0.9);
}

.toast.success {
    background-color: rgba(76, 175, 80, 0.9);
}

.toast.warning {
    background-color: rgba(255, 152, 0, 0.9);
}

.toast.error {
    background-color: rgba(244, 67, 54, 0.9);
}

@keyframes fadeIn {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }
}

/* 响应式设计 */
@media (max-width: 375px) {
    .theme-list {
        grid-template-columns: repeat(2, 1fr);
    }

    .logo {
        font-size: 18px;
    }

    .search-box {
        margin: 0 10px;
    }
}
</style>